import React, { memo, useState, useCallback, useEffect } from "react";
import sty from "./sty.module.css";
import { SearchBar } from "antd-mobile";
import ResTabs from "./child/resTabs";
import { fatory } from "@/utils/local";
import { reqHotSearch, reqSearchSuggest } from "@/api/search";
const Shistory = fatory("searchHistory", "[]");
let timer = null;
const Search = () => {
  const [keywords, setKeyWords] = useState("");
  const [isFocus, setIsFocus] = useState(false);
  const [isSearch, setIsSearch] = useState(false);
  const [suggestList, setSuggestList] = useState([]);
  const [hotList, setHotList] = useState([]);
  const [searchHistory, setSearchHistory] = useState(Shistory.getItem());

  useEffect(() => {
    reqHotSearch().then((res) => {
      if (res.code === 200) {
        setHotList(res.result.hots);
      }
    });
  }, []);
  useEffect(() => {
    return () => {
      Shistory.setItem(searchHistory);
    };
  }, [searchHistory]);

  const getSuggestList = async (keywords) => {
    if (!keywords.length) {
      return;
    }
    const res = await reqSearchSuggest(keywords);
    if (res.code === 200) {
      setSuggestList(res.result.allMatch);
    }
  };
  const handleChange = useCallback((keyword) => {
    keyword = keyword.trim();
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      getSuggestList(keyword);
    }, 200);
    setKeyWords(keyword);
    isSearch && setIsSearch(false);
  }, []);
  const addHistory = (keyword) => {
    const i = searchHistory.findIndex((v) => v === keyword);
    if (i !== -1 && i !== 0) {
      searchHistory.splice(i, 1);
    }

    const list = searchHistory;
    list.unshift(keyword);
    setSearchHistory(list);
  };
  const search = useCallback((keyword) => {
    setKeyWords(keyword);
    setIsSearch(true);
    addHistory(keyword);
  }, []);
  const removeHistory = (i) => {
    console.log("i", i);
    const list = searchHistory;
    console.log(list);
    list.splice(i, 1);
    console.log(list);
    setSearchHistory(list);
  };
  const FocusBox = () =>
    isSearch ? (
      <ResTabs keywords={keywords} />
    ) : (
      <ul className={sty.suggestList}>
        {suggestList &&
          suggestList.map((v) => (
            <li key={v.keyword} onClick={() => search(v.keyword)}>
              <i className="iconfont icon-sousuo1"></i>
              <span>{v.keyword}</span>
            </li>
          ))}
      </ul>
    );
  const BlurBox = (
    <div className={sty.searchBox}>
      <div style={{ display: hotList.length ? "" : "none" }}>热门搜索</div>
      <ul className={sty.hotSearch}>
        {hotList.length
          ? hotList.map((v) => (
              <li onClick={() => search(v.first)} key={v.first}>
                {v.first}
              </li>
            ))
          : null}
      </ul>
      <ul className={sty.searchHistory}>
        {searchHistory.length
          ? searchHistory.map((v, i) => (
              <li key={v}>
                <i className="iconfont icon-lishibisai"></i>
                <div onClick={() => search(v)}> {v}</div>
                <i
                  className="iconfont icon-lvzhou_shanchu_lajitong"
                  onClick={() => removeHistory(i)}
                ></i>
              </li>
            ))
          : null}
      </ul>
    </div>
  );

  return (
    <div className={sty.root}>
      <SearchBar
        value={keywords}
        onChange={handleChange}
        placeholder={"搜索歌手、歌曲、专辑"}
        onBlur={() => setIsFocus(false)}
        onFocus={() => setIsFocus(true)}
      />
      {keywords || isFocus ? <FocusBox /> : BlurBox}
    </div>
  );
};
export default memo(Search);
